// Establish a cache name
const cacheName = "MyFancyCacheName_v1";

const precachedAssets = ["/1.jpg"];

self.addEventListener("install", (event) => {
  // Precache assets on install
  event.waitUntil(
    caches.open(cacheName).then((cache) => {
      return cache.addAll(precachedAssets);
    })
  );
});

self.addEventListener("fetch", async (event) => {
  console.log("interceptor by service worker: ", event.request);
  event.respondWith(
    caches.open(cacheName).then((cache) => {
      return cache.match(event.request).then((cachedResponse) => {
        if (cachedResponse) {
          console.log("matched: ", event.request.url);
          return cachedResponse;
        }
        return fetch(event.request.url).then((fetchedResponse) => {
          console.log("not cached: ", event.request.url);
          cache.put(event.request, fetchedResponse.clone());

          return fetchedResponse;
        });
      });
    })
  );
});
